/*
 * @Description: 
 * @Version: 1.0
 * @Autor: gaoluo
 * @Date: 2021-08-19 15:08:01
 * @LastEditors: gaoluo
 * @LastEditTime: 2021-11-17 19:50:49
 * @FilePath: /nhw/src/router/index.js
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import { start, done, configure } from 'nprogress';
import { isValid, getToken, setToken } from '@/utils/token.js'
import routes from './routes.js';
import { Toast } from 'vant';
import 'nprogress/nprogress.css'
Vue.use(VueRouter)

//配置加载器属性
configure({
  trickleSpeed: 20,
  showSpinner: false
})

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


//导航守卫
router.beforeEach((to, from, next) => {
  //加载动画开始
  start();

  // token过期或者不存在 且 要跳转的不是 login页面 跳转登录页面登录
  try {
    if (!isValid(getToken()) && from.name !== 'Login' && "Login" !== to.name) {
      Toast('登录过期,请重新登录！')
      setTimeout(() => {
        next({ name: 'Login' });
      }, 500);
    }
    else {
      next()
    }
  } catch (error) {
    console.log(error)
  }
})

router.afterEach((to, from) => {
  //加载动画结束
  done()
})

router.onError((error) => {
  console.log('touter error', error);
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  const targetPath = router.history.pending.fullPath;
  if (isChunkLoadFailed) {
    router.replace(targetPath);
  }
});


export default router
